import { BadRequestException, Controller, Get, Param } from '@nestjs/common';
import { UsersService } from '../users/users.service';
import { ErrCode } from './code2session.interface';
import { TokenService } from './token.service';

@Controller('token')
export class TokenController {
  constructor(
    private tokenService: TokenService,
    private usersService: UsersService,
  ) {}

  @Get(':code')
  async findOne(@Param('code') code: string) {
    const {
      data: { openid, errcode },
    } = await this.tokenService.code2Session(code);

    // 获取 code2Session 失败，异常处理
    switch (errcode) {
      case ErrCode.Busy:
        throw new BadRequestException('请开发者稍候再试', '系统繁忙');

      case ErrCode.Invalid:
        throw new BadRequestException('请使用有效的 code', 'code 无效');

      case ErrCode.ApiLimit:
        throw new BadRequestException('每个用户每分钟100次', '频率限制');

      case ErrCode.Used:
        throw new BadRequestException('请换一个 code', 'code 已被使用过');

      case ErrCode.Missing:
        throw new BadRequestException('请填写 code', '缺少 code');
    }

    const { _id } = await this.usersService.findOneByOpenid(openid);

    return this.tokenService.login(_id);
  }
}
